<?php
// $Id$

/**
 * Controller_Address 控制器
 */
class Controller_Address extends Controller_Abstract
{

	function actionIndex()
	{
        // 为 $this->_view 指定的值将会传递数据到视图中
		# $this->_view['text'] = 'Hello!';
		$address = Address::find('user_id = ?', $this->_app->currentUserObject()->id())->getAll();
		$this->_view['address'] = $address;
	}
	
	function actionCreate()
	{
		$form = new Form_Address(url('address/create'));
		
		if($this->_context->isPOST() && $form->validate($_POST))
		{
			$user = $this->_app->currentUserObject();
			
			$address = $user->createAddress($form->values());
			$address->save();
			return $this->_redirect(url('address/index'));
		}
		
		$this->_view['form'] = $form;
	}
	
	function actionEdit()
	{
		$address = Address::find('address_id = ? AND [owner.user_id] = ?',
			$this->_context->address_id,
			$this->_app->currentUserObject()->id())->query();
			
		if(!$address->id())
		{
			return $this->_redirect(url('address/index'));
		}
		
		$form = new Form_Address(url('address/edit'));
		$form->_subject = '编辑地址';
//		$form->add(QForm::ELEMENT, 'is_default', array(
//			'_ui'	=> 'checkbox',
//			'checked_by_value'	=> true,
//			'caption'	=> '设为默认收货地址',
//		));
		$form->add(QForm::ELEMENT, 'address_id', array('_ui' => 'hidden'));
		if($this->_context->isPOST() && $form->validate($_POST))
		{		
//			echo('address<br>');
			$address->changeProps($form->values());
//			echo('address<br>');
//			$this->set_default($form['is_default']->value, $adddress);
			$address->save();
			return $this->_redirect(url('address/index'));
		}
		elseif(!$this->_context->isPOST())
		{
			$form->import($address);
		}
		$this->_view['form'] = $form;
		$this->_viewname = 'create';

	}
	
	
	function actionSetdefault()
	{
//		echo('default<br>');
		$address = Address::find('address_id = ? AND [owner.user_id] = ?',
		$this->_context->address_id,
		$this->_app->currentUserObject()->id())->query();
		$this->set_default(true, $address);
		$address->save();
		return $this->_redirect(url('address/index'));
	}
	
	function set_default($default, $address)
	{
		$default = (bool)$default;
		$address = $address;
		if(!$address->id())
		{
			return $this->_redirect(url('address/index'));
		}
		if(!$address->is_default)
		{
			$add = Address::find('user_id = ?', $this->_app->currentUserObject()->id())->getAll();
			foreach($add as $add)
			{
				if($add->is_default)
				{
					$add->set_default(false);
					$add->save();
				}
			}
		}
		$address->set_default(true);
	}
	
	function actionDelete()
	{
		Address::meta()->destroyWhere('address_id = ? AND [owner.user_id] = ?',
			$this->_context->address_id,
			$this->_app->currentUserObject()->id());
			
		return $this->_redirectMessage(
			'删除成功',
			'您成功删除一个收货地址',
			url('address/index'));
	}
}


